package com.ys.controller.api.finance;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliDrawing;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwWanliDrawingService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 万里汇提款单
 */
@Controller
@RequestMapping("/api/inter/tcwWanliDrawing")
public class ApiInterTcwWanliDrawingController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwWanliDrawingController.class);

    @Autowired
    private CommonApiService<TcwWanliDrawing> commonApiService;

    @Autowired
    private TcwWanliDrawingService tcwWanliDrawingService;

    @Autowired
    private YspTaskService yspTaskService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliDrawing setSeachSql(TcwWanliDrawing cond,String conditions){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

        .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime")//审核时间

        .addLeftJoin("TCW_DepositPlatform D ON D.Code = A.DepositPlatformCode ")//万里汇账号资金
                .addField("D.PlatformName AS platformName")//收款平台名称
                .addField("D.Code AS depositPlatformCode")//账号编码
                .addField("D.Name AS name")//账号名称
                .addField("D.Mid AS depositPlatformMid")

                .addLeftJoin("TB_CompanyInfo O ON O.Vid = D.CompanyVid ")//公司信息表
                .addField("O.Vname AS vname")//公司名称

        .addLeftJoin("TCW_WanliDrawingItem S ON S.Pbid = A.Bid ")//子表信息
                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = S.CompanyBankInfoId ")//公司银行账户管理表

                .addField("CB.Vyhzhmc AS vyhzhmc")//收款账户名称
                .addField("S.OutCurrencyCode AS outCurrencyCode")//汇出币种
                .addField("S.OutSum AS outSum")//汇出金额
                .addField("S.ExchangeRate AS exchangeRate")//汇率
                .addField("S.ProceduresRatio AS proceduresRatio")//手续费比例
                .addField("S.ProceduresSum AS proceduresSum")//手续费（汇出币种）
                .addField("S.InCurrencyCode AS inCurrencyCode")//汇入币种
                .addField("S.InSum AS inSum")//汇入金额

        //排序
        .setOrderby("A.Bid DESC");

        //查询条件
        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
        if (nameLinked != null){
            cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
        }

        cond = commonApiService.dataAuth(MenuId.TCW_WanliDrawing, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwWanliDrawing:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwWanliDrawing cond,String conditions
    ){
        try {
            cond = setSeachSql(cond,conditions);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliDrawing cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,conditions);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_WanliDrawing)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwWanliDrawing> util = new ExportExcelUtils<>(new TcwWanliDrawing());
            String toFilePath = util.exportExcel(listData, listField, "万里汇提款单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwWanliDrawingService.add(params,MenuId.TCW_WanliDrawing);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwWanliDrawingService.update(params,MenuId.TCW_WanliDrawing);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwWanliDrawingService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除列表
     */
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwWanliDrawingService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwWanliDrawingService.flowPass(id, ShiroUtils.getUserId());
        }catch (IllegalArgumentException e) {
            return R.error(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            TcwWanliDrawing entity = new TcwWanliDrawing().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            TcwWanliDrawing entity = new TcwWanliDrawing().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }



}